package cn.itcast.shop.utils.verifycode;

import java.awt.image.BufferedImage;
import java.io.IOException;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

import cn.mytools.vcode.utils.VerifyCode;
/**
 * 验证码工具类
 */
public class VerifyCodeAction extends ActionSupport{
	
	private static final long serialVersionUID = -3382070498814376435L;
	
	/**
	 * 生成验证码
	 */
	public String execute() throws IOException{
		VerifyCode vc = new VerifyCode();//创建一个新的验证码对象
		BufferedImage image = vc.getImage();//获取一次性验证码图片
		VerifyCode.output(image, ServletActionContext.getResponse().getOutputStream());//把图片写到响应流中
		// 把文本保存到session中，为LoginServlet验证做准备
		ServletActionContext.getRequest().getSession().setAttribute("vCode", vc.getText());
		return NONE;
	}
	/**
	 * 验证码校验
	 * @return
	 * @throws IOException
	 */
	public String validation() throws IOException {
		String verifyCode = ServletActionContext.getRequest().getParameter("verifyCode");//获取表单中输入的验证码
		String vCode = (String) ServletActionContext.getRequest().getSession().getAttribute("vCode");//获取session中的验证码
		if(verifyCode.equalsIgnoreCase(vCode)){	//校验
			ServletActionContext.getResponse().getWriter().println("true");
		}else {
			ServletActionContext.getResponse().getWriter().println("false");
		}
		return NONE;
	}
	
}
